# -*- coding: utf-8 -*-
# @日期    : 2020/11/30 20:15
# @作者  : 万方名
# @FileName: feature_1.py

import os
import re
import requests
import pandas as pd
import tkinter
import time

from tkinter import filedialog
from tkinter import *
from tkinter.scrolledtext import ScrolledText
from bs4 import BeautifulSoup


def get_data(stock_code):
    url_sz = 'https://xueqiu.com/S/SZ{}'.format(stock_code)
    url_sh = 'https://xueqiu.com/S/SH{}'.format(stock_code)

    # 获取方法F12
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36 Edg/87.0.664.47"
    }

    response = requests.get(url_sz, headers=headers)
    if response.status_code == 404:
        response = requests.get(url_sh, headers=headers)
    return response.text


def parse_data(data):
    parsed_data = BeautifulSoup(data, 'html5lib')
    scripts = parsed_data.select('script')
    gold_script = str(scripts[11])
    # 获取股票名
    stock_name = parsed_data.title.string[:parsed_data.title.string.find('股票股价')]
    print(stock_name)
    # 获取总市值
    value_start = re.search('总市值', gold_script, flags=0).span()[0]
    str_value = gold_script[value_start:value_start + 20]
    str_value_sub = re.sub(r'[^0-9.]', '', str_value)
    value = str_value_sub + '亿'

    # 获取股息率
    dividend_rate_start = re.search('股息率', gold_script, flags=0).span()[0]
    str_dividend_rate = gold_script[dividend_rate_start:dividend_rate_start + 20]
    str_dividend_rate_sub = re.sub(r'[^0-9.]', '', str_dividend_rate)
    dividend_rate = str_dividend_rate_sub + '%'

    # 获取当前价格
    current_start = re.search('current"', gold_script, flags=0).span()[0]
    str_current = gold_script[current_start:current_start + 20]
    current = re.sub(r'[^0-9.]', '', str_current)

    # 获取市盈率
    PER_start = re.search('市盈率\(动', gold_script, flags=0).span()[0]
    str_PER = gold_script[PER_start:PER_start + 20]
    PER = re.sub(r'[^0-9.]', '', str_PER)

    return stock_name, value, dividend_rate, current, PER


def low_buy_price_red(s):
    color = 'red' if float(s) < 0.1 else 'black'
    return f"color:{color}"


def green_descend(col):
    col_list = []
    for s in col:
        if float(s) < -0.05:
            col_list.append('background-color:lime')
        elif float(s) > 0.05:
            col_list.append('background-color:red')
        else:
            col_list.append('background-color:white')
    return col_list


def red_ascend(col):
    return ['background-color:red' if float(s) > 0.05 else 'background-color:white' for s in col]


def format_(s):
    return str(s * 100)[:5] + '%'


def main():
    # 读取股票代码
    root = tkinter.Tk()  # 创建一个Tkinter.Tk()实例
    root.withdraw()  # 将Tkinter.Tk()实例隐藏
    default_dir = r"文件路径"
    code_csv_path = filedialog.askopenfilename(title=u'选择文件', initialdir=(os.path.expanduser(default_dir)))
    print(code_csv_path)
    save_path_tmp = code_csv_path.split('/')[:-1]
    save_path = ''
    for line in save_path_tmp:
        save_path += line
        save_path += '/'
    code_df = pd.read_excel(code_csv_path)

    stock_name_list = []
    value_list = []
    dividend_rate_list = []
    current_list = []
    PER_list = []
    buy_point_list = []
    point_ratio_list = []
    change_ratio_list = []

    for index in range(len(code_df)):
        stock_code = str(code_df['股票代码'][index])
        buy_point = code_df['买点'][index]
        select_price = code_df['选股时价格'][index]

        if len(stock_code) < 6:
            stock_code = '0' * (6 - len(stock_code)) + stock_code

        data = get_data(stock_code)
        stock_name, value, dividend_rate, current, PER = parse_data(data)

        stock_name_list.append(stock_name)
        value_list.append(value)
        dividend_rate_list.append(dividend_rate)
        current_list.append(current)
        PER_list.append(PER)
        buy_point_list.append(buy_point)
        point_ratio_list.append((float(current) - buy_point) / float(current))
        change_ratio_list.append((float(current) - float(select_price)) / float(select_price))

    # 保存为csv,格式化成2016-03-20 11:45:39形式
    save_path = '{}stock_logging-{}.xlsx'.format(save_path, time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()))
    data_dict = {'股票名': stock_name_list, '总市值': value_list, '股息率': dividend_rate_list, '现价': current_list,
                 '市盈率': PER_list, '买点': buy_point_list, '离买点的百分点': point_ratio_list, '选股至今': change_ratio_list}

    data_df = pd.DataFrame(data_dict)
    data_df = data_df.sort_values(by='离买点的百分点')

    data_df = data_df.style.applymap(low_buy_price_red, subset=['离买点的百分点']).apply(green_descend, subset=['选股至今'])

    data_df.to_excel(save_path, index=None)
    data_df = pd.read_excel(save_path)


if __name__ == '__main__':
    main()
